﻿using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Packaging;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Xps.Packaging;
using System.Windows.Xps.Serialization;
using TeacherLeftHand.Model;
using TeacherLeftHand.Model;
using System.Windows.Controls;
using System.Windows.Documents;
using log4net;
using Microsoft.Office.Interop.Word;
using System.Reflection;

namespace TeacherLeftHand.Util
{
    internal class FileExporter
    {
        #region Constant

        public static string StrCodeName = "TLHTLHTLHFU";

        #endregion


        #region Variables

        protected static readonly ILog Log = LogManager.GetLogger(typeof(MainWindow));

        #endregion

        #region Methods

        /// <summary>
        /// Export richtext format to doc,docx,rtf,xps format
        /// </summary>
        /// <param name="richTextBox">Specify the richtextbox</param>
        /// <param name="fileType">Specify the file type</param>
        /// <param name="fileName">Specify the file name</param>
        /// <returns>Boolean</returns>
        public static bool Export(RichTextBox richTextBox, string fileType, string fileName)
        {
            try
            {
                //if (fileType.Trim().Substring(fileType.Length - 4, 4).Equals("docx"))
                if (fileType.Trim().Equals(".docx"))
                {
                    if(ExportToRtf(richTextBox,fileName, fileType))
                    {
                        if (ConvertToDoc(fileName, fileType))
                            return true;
                        return false;
                    }
                    return false;
                }
                if (fileType.Trim().Equals(".doc"))
                {
                    if (ExportToRtf(richTextBox, fileName, fileType))
                    {
                        if (ConvertToDoc(fileName, fileType))
                            return true;
                        return false;
                    }
                    return false;
                }
                if (fileType.Trim().Equals(".pdf"))
                {
                    if (ExportToRtf(richTextBox, fileName, fileType))
                    {
                        if (ConvertToPdf(fileName, fileType))
                            return true;
                        return false;
                    }
                    return false;
                }
                if (fileType.Trim().Equals(".rtf"))
                {
                    if (ExportToRtf(richTextBox, fileName, fileType))
                    {
                        return true;
                    }
                    return false;
                }
                if (fileType.Trim().Equals(".xps"))
                {
                    if (ConvertToXps(richTextBox,fileName))
                    {
                        return true;
                    }
                    return false;
                }
                return false;
            }
            catch (Exception ex)
            {
                Log.Debug(ex.Message);
            }
            return false;

        }

        /// <summary>
        /// Export richtext format to rtf format
        /// </summary>
        /// <param name="richTextBox">Specify the richtextbox</param>
        /// <param name="fileName">Specify the file name</param>
        /// <param name="fileType">Specify the file type</param>
        /// <returns>Boolean</returns>
        public static bool ExportToRtf(RichTextBox richTextBox, string fileName, string fileType)
        {
            try
            {
                var range = new TextRange(richTextBox.Document.ContentStart, richTextBox.Document.ContentEnd);
                var fStream = new FileStream(@fileName + StrCodeName + ".rtf", FileMode.CreateNew);
                range.Save(fStream, DataFormats.Rtf);
                fStream.Close();
                
                if(!fileType.Trim().Equals(".rtf"))
                {
                    File.SetAttributes(@fileName + StrCodeName + ".rtf", FileAttributes.Hidden);   
                }

                return true;
            }
            catch (Exception ex)
            {
                Log.Debug(ex.Message);
            }

            return false;

        }

        /// <summary>
        /// Convert RTF format to Doc format
        /// </summary>
        /// <param name="fileName">Specify the path to save file</param>
        /// <param name="fileType">Specify the path to file type</param>
        /// <returns>Boolean</returns>
        public static bool ConvertToDoc(string fileName, string fileType)
        {
            try
            {
                var wordApp = new Microsoft.Office.Interop.Word.Application();
                var currentDoc = wordApp.Documents.Open(@fileName + StrCodeName + ".rtf", Format: WdOpenFormat.wdOpenFormatRTF);

                fileName = fileName.Replace(StrCodeName, "");

                currentDoc.Convert();
                currentDoc.SaveAs(@fileName + fileType.Trim(), WdSaveFormat.wdFormatDocumentDefault);
                currentDoc.Close();
                wordApp.Quit();

                File.Delete(@fileName + StrCodeName + ".rtf");

                return true;
            }
            catch (Exception ex)
            {
                Log.Debug(ex.Message);
            }

            return false;

        }


        /// <summary>
        /// Convert RTF format to PDF format
        /// </summary>
        /// <param name="fileName">Specify the path to save file</param>
        /// <param name="fileType">Specify the path to file type</param>
        /// <returns>Boolean</returns>
        public static bool ConvertToPdf(string fileName, string fileType)
        {
            try
            {
                var wordApp = new Microsoft.Office.Interop.Word.Application();
                object oMissing = Missing.Value;
                var currentDoc = wordApp.Documents.Open(@fileName + StrCodeName + ".rtf", Format: WdOpenFormat.wdOpenFormatRTF);

                fileName = fileName.Replace(StrCodeName, "");

                //currentDoc.Convert();
                currentDoc.Activate();
                currentDoc.SaveAs(@fileName + fileType.Trim(), WdSaveFormat.wdFormatPDF);

                object saveChanges = Microsoft.Office.Interop.Word.WdSaveOptions.wdSaveChanges;
                ((Microsoft.Office.Interop.Word._Document)currentDoc).Close(ref saveChanges, ref oMissing, ref oMissing);

                //currentDoc.Close();
                wordApp.Quit();

                File.Delete(@fileName + StrCodeName + ".rtf");

                return true;
            }
            catch (Exception ex)
            {
                Log.Debug(ex.Message);
            }

            return false;

        }


        /// <summary>
        /// Create XPS file
        /// </summary>
        /// <param name="richTextBox">Specify rich text box</param>
        /// <param name="fileName">Specify the path to file name</param>
        /// <returns>Boolean</returns>
        public static bool ConvertToXps(RichTextBox richTextBox,string fileName)
        {
            try
            {
                //create XPS type
                string path = fileName+".xps";
                FlowDocument document = richTextBox.Document;

                using (var package = Package.Open(path, FileMode.Create))
                {
                    using (var xpsDoc = new XpsDocument(
                        package, System.IO.Packaging.CompressionOption.Maximum))
                    {
                        var xpsSm = new XpsSerializationManager(
                            new XpsPackagingPolicy(xpsDoc), false);
                        DocumentPaginator dp =
                            ((IDocumentPaginatorSource)document).DocumentPaginator;
                        xpsSm.SaveAsXaml(dp);
                    }
                }

                return true;
            }
            catch (Exception ex)
            {
                Log.Debug(ex.Message);
            }

            return false;
        }

        #endregion 
       
    }
}
